package project2.resources;

import project2.config.Config;
import project2.entity.Score;
import project2.util.FileUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 分数管理器
 * 使用静态数据暂存分数
 * 每次添加操作都会同步到分数文件中
 */
public class Scores {
    public static List<Score> scoreList;

    static {
        try {
            scoreList = FileUtil.readScore(Config.SCORE_FILE);
        } catch (Exception e) {
            scoreList = new ArrayList<>();
        }
    }

    public static void addScore(int score, long lastMilliSeconds) throws IOException {
        Score s = new Score(new Date(System.currentTimeMillis()), score, lastMilliSeconds);
        int size = scoreList.size();
        if (scoreList.contains(s)) {
            return;
        }
        if (size < Config.MAX_SCORE_COUNT) {
            scoreList.add(s);
        } else {
            Score lastScore = scoreList.get(size - 1);
            if (s.compareTo(lastScore) > 0) {
                scoreList.remove(lastScore);
                scoreList.add(s);
            }
        }
        Collections.sort(scoreList);
        Collections.reverse(scoreList);
        FileUtil.writeScore(scoreList, Config.SCORE_FILE);
    }
}
